package com.lp.multi.thread.example06;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: lp
 * @create: 2021-06-22 17:14
 * @description: ReentrantLock测试
 * ReentrantLock是显示锁，synchronized是隐式锁
 */
public class ReentrantLockTest {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket).start();
        new Thread(ticket).start();
        new Thread(ticket).start();
    }
}

class Ticket implements Runnable{
    private int ticketNum = 10;
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            lock.lock();
            try{
                if(ticketNum >0){
                    //模拟延迟出票
                    Thread.sleep(1000);
                    System.out.println(ticketNum--);
                }else{
                    return;
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }
}
